{% extends "base.html" %}

{% block title %}脚本管理 - XbyJob{% endblock %}


{% block content %}
<style>
.sort-arrows {
    margin-left: 5px;
    font-size: 0.8em;
}

.sort-arrows i {
    opacity: 0.3;
    margin: 0 1px;
}

.sort-arrows i.active {
    opacity: 1;
    color: #007bff;
}

.table th {
    border-top: none;
    vertical-align: middle;
}

.table td {
    vertical-align: middle;
}

.item-type-badge {
    font-size: 0.75em;
}

.created-time {
    font-size: 0.9em;
    color: #6c757d;
}

.table-hover tbody tr:hover {
    background-color: rgba(0, 123, 255, 0.05);
}



/* 脚本操作按钮样式 */
.script-actions {
    display: flex !important;
    gap: 6px !important;
    align-items: center !important;
}

td .script-actions .action-btn,
.script-actions .action-btn.btn,
button.action-btn {
    display: inline-flex !important;
    align-items: center !important;
    justify-content: center !important;
    width: 32px !important;
    height: 32px !important;
    border: none !important;
    border-radius: 50% !important;
    font-size: 14px !important;
    text-decoration: none !important;
    cursor: pointer !important;
    transition: all 0.2s ease !important;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1) !important;
    padding: 0 !important;
    margin: 0 !important;
    min-width: 32px !important;
    max-width: 32px !important;
    min-height: 32px !important;
    max-height: 32px !important;
}

td .script-actions .action-btn:hover,
.script-actions .action-btn.btn:hover,
button.action-btn:hover {
    transform: translateY(-1px) !important;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2) !important;
    text-decoration: none !important;
}

td .script-actions .action-btn:active,
.script-actions .action-btn.btn:active,
button.action-btn:active {
    transform: translateY(0) !important;
}

td .script-actions .action-btn span,
.script-actions .action-btn.btn span,
button.action-btn span {
    display: none !important;
}

/* 编辑按钮 */
td .script-actions .edit-btn,
.script-actions .edit-btn.btn,
button.edit-btn {
    background-color: #007bff !important;
    color: white !important;
}

td .script-actions .edit-btn:hover,
.script-actions .edit-btn.btn:hover,
button.edit-btn:hover {
    background-color: #0056b3 !important;
    color: white !important;
}

/* 下载按钮 */
td .script-actions .download-btn,
.script-actions .download-btn.btn,
button.download-btn {
    background-color: #28a745 !important;
    color: white !important;
}

td .script-actions .download-btn:hover,
.script-actions .download-btn.btn:hover,
button.download-btn:hover {
    background-color: #1e7e34 !important;
    color: white !important;
}

/* 测试按钮 */
td .script-actions .test-btn,
.script-actions .test-btn.btn,
button.test-btn {
    background-color: #17a2b8 !important;
    color: white !important;
}

td .script-actions .test-btn:hover,
.script-actions .test-btn.btn:hover,
button.test-btn:hover {
    background-color: #138496 !important;
    color: white !important;
}

/* 删除按钮 */
td .script-actions .delete-btn,
.script-actions .delete-btn.btn,
button.delete-btn {
    background-color: #dc3545 !important;
    color: white !important;
}

td .script-actions .delete-btn:hover,
.script-actions .delete-btn.btn:hover,
button.delete-btn:hover {
    background-color: #c82333 !important;
    color: white !important;
}
</style>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">脚本管理</h1>
    <div class="btn-toolbar mb-2 mb-md-0">
        <div class="btn-group me-2">
            <button type="button" class="btn btn-primary" onclick="createFolder()">
                <i class="fas fa-folder-plus me-1"></i>创建文件夹
            </button>
            <button type="button" class="btn btn-success" onclick="uploadScript()">
                <i class="fas fa-upload me-1"></i>上传脚本
            </button>
            <button type="button" class="btn btn-outline-secondary" onclick="refreshScripts()">
                <i class="fas fa-sync-alt me-1"></i>刷新
            </button>
        </div>
    </div>
</div>

<!-- 面包屑导航 -->
<nav aria-label="breadcrumb" class="mb-3">
    <ol class="breadcrumb" id="breadcrumb">
        <li class="breadcrumb-item"><a href="#" onclick="navigateToFolder(null)">根目录</a></li>
    </ol>
</nav>

<!-- 批量操作工具栏 -->
<div class="row mb-3" id="batchToolbar" style="display: none;">
    <div class="col-12">
        <div class="card border-primary">
            <div class="card-body py-2">
                <div class="d-flex justify-content-between align-items-center">
                    <div class="d-flex align-items-center">
                        <span class="me-3">已选择 <span id="selectedCount">0</span> 项</span>
                        <div class="btn-group btn-group-sm">
                            <button type="button" class="btn btn-outline-primary" onclick="selectAll()">
                                <i class="fas fa-check-square me-1"></i>全选
                            </button>
                            <button type="button" class="btn btn-outline-secondary" onclick="clearSelection()">
                                <i class="fas fa-square me-1"></i>取消选择
                            </button>
                        </div>
                    </div>
                    <div class="btn-group btn-group-sm">
                        <button type="button" class="btn btn-danger" onclick="batchDeleteScripts()" id="batchDeleteScriptsBtn" style="display: none;">
                            <i class="fas fa-trash me-1"></i>批量删除脚本
                        </button>
                        <button type="button" class="btn btn-warning" onclick="batchDeleteFolders(false)" id="batchDeleteFoldersBtn" style="display: none;">
                            <i class="fas fa-folder-minus me-1"></i>批量删除文件夹
                        </button>
                        <button type="button" class="btn btn-danger" onclick="batchDeleteFolders(true)" id="batchForceDeleteFoldersBtn" style="display: none;">
                            <i class="fas fa-exclamation-triangle me-1"></i>强制删除文件夹
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 脚本列表 -->
<div class="row">
    <!-- 文件夹和脚本列表 -->
    <div class="col-md-8">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h6 class="card-title mb-0">文件夹和脚本</h6>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="batchModeToggle">
                    <label class="form-check-label" for="batchModeToggle">
                        批量操作模式
                    </label>
                </div>
            </div>
            <div class="card-body">
                <!-- 表格头部 -->
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th style="width: 40px;">
                                    <div class="form-check" id="selectAllContainer" style="display: none;">
                                        <input class="form-check-input" type="checkbox" id="selectAllCheckbox" onchange="toggleSelectAll()">
                                    </div>
                                </th>
                                <th style="cursor: pointer;" onclick="sortBy('name')">
                                    名称
                                    <span class="sort-arrows">
                                        <i class="fas fa-sort-up" id="sort-name-asc"></i>
                                        <i class="fas fa-sort-down" id="sort-name-desc"></i>
                                    </span>
                                </th>
                                <th style="cursor: pointer;" onclick="sortBy('type')">
                                    类型
                                    <span class="sort-arrows">
                                        <i class="fas fa-sort-up" id="sort-type-asc"></i>
                                        <i class="fas fa-sort-down" id="sort-type-desc"></i>
                                    </span>
                                </th>
                                <th style="cursor: pointer;" onclick="sortBy('created_at')">
                                    创建时间
                                    <span class="sort-arrows">
                                        <i class="fas fa-sort-up" id="sort-created_at-asc" class="active"></i>
                                        <i class="fas fa-sort-down" id="sort-created_at-desc"></i>
                                    </span>
                                </th>
                                <th style="width: 120px;">操作</th>
                            </tr>
                        </thead>
                        <tbody id="scriptsContainer">
                            <tr>
                                <td colspan="5" class="text-center">
                                    <div class="spinner-border text-primary" role="status">
                                        <span class="visually-hidden">加载中...</span>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 脚本预览 -->
    <div class="col-md-4">
        <div class="card">
            <div class="card-header">
                <h6 class="card-title mb-0">脚本预览</h6>
            </div>
            <div class="card-body" id="scriptPreview">
                <p class="text-muted">选择一个脚本以查看内容</p>
            </div>
        </div>
    </div>
</div>

<!-- 创建文件夹模态框 -->
<div class="modal fade" id="createFolderModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">创建文件夹</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="folderForm">
                    <div class="mb-3">
                        <label for="folderName" class="form-label">文件夹名称</label>
                        <input type="text" class="form-control" id="folderName" required>
                    </div>
                    <div class="mb-3">
                        <label for="folderDescription" class="form-label">描述</label>
                        <textarea class="form-control" id="folderDescription" rows="3"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveFolder()">创建</button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑文件夹模态框 -->
<div class="modal fade" id="editFolderModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">编辑文件夹</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="editFolderForm">
                    <div class="mb-3">
                        <label for="editFolderName" class="form-label">文件夹名称</label>
                        <input type="text" class="form-control" id="editFolderName" required>
                    </div>
                    <div class="mb-3">
                        <label for="editFolderDescription" class="form-label">描述</label>
                        <textarea class="form-control" id="editFolderDescription" rows="3"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="updateFolder()">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 上传脚本模态框 -->
<div class="modal fade" id="uploadScriptModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">上传脚本</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="uploadScriptForm" enctype="multipart/form-data">
                    <div class="mb-3">
                        <label for="scriptFile" class="form-label">选择脚本文件</label>
                        <input type="file" class="form-control" id="scriptFile" accept=".py" required>
                        <div class="form-text">支持的文件类型：.py</div>
                    </div>
                    <div class="mb-3">
                        <label for="scriptFolder" class="form-label">目标文件夹</label>
                        <div class="border rounded p-3" style="max-height: 200px; overflow-y: auto;">
                            <div id="folderTreeContainer">
                                <div class="folder-item" data-folder-id="" style="cursor: pointer; padding: 5px; border-radius: 3px;">
                                    <i class="fas fa-folder text-warning me-2"></i>
                                    <span>根目录</span>
                                </div>
                            </div>
                        </div>
                        <input type="hidden" id="scriptFolder" value="">
                    </div>
                    <div class="mb-3">
                        <label for="scriptDescription" class="form-label">描述</label>
                        <textarea class="form-control" id="scriptDescription" rows="3" placeholder="可选：描述脚本的功能和用途"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-success" onclick="submitUpload()">上传</button>
            </div>
        </div>
    </div>
</div>
    </div>
</div>

{% endblock %}

{% block extra_js %}
<script>
let currentFolderId = null;
let allFolders = [];
let rootScripts = []; // 存储根目录下的脚本
let currentPath = []; // 用于记录当前路径

$(document).ready(function() {
    loadScripts();
    
    // 文件上传相关监听器
    $('#scriptFile').on('change', function() {
        const file = this.files[0];
        if (file) {
            // 验证文件类型
            const allowedTypes = ['.py'];
            const fileExtension = '.' + file.name.split('.').pop().toLowerCase();
            if (!allowedTypes.includes(fileExtension)) {
                showAlert('不支持的文件类型，请选择 .py 文件', 'danger');
                this.value = '';
            }
        }
    });
});

function loadScripts() {
    // 显示加载指示器
    $('#scriptsContainer').html('<div class="text-center p-5"><div class="spinner-border" role="status"></div><p class="mt-2">加载中...</p></div>');
    
    $.get('/api/script-folders')
        .done(function(response) {
            if (response.success) {
                // 处理新的API响应格式
                allFolders = response.data.folders || [];
                rootScripts = response.data.root_scripts || [];
                renderFolderTree(allFolders);
                updateFolderSelect(allFolders);
            } else {
                showAlert('获取脚本列表失败: ' + response.message, 'danger');
                // 清除加载指示器，显示错误信息
                $('#scriptsContainer').html('<div class="alert alert-danger">加载失败: ' + response.message + '</div>');
            }
        })
        .fail(function(xhr, status, error) {
            console.error('API请求失败:', status, error);
            showAlert('网络错误，请稍后重试', 'danger');
            // 清除加载指示器，显示错误信息
            $('#scriptsContainer').html('<div class="alert alert-danger">网络错误，请稍后重试</div>');
        });
}

function updateFolderSelect(folders) {
    const container = $('#folderTreeContainer');
    container.empty();
    
    // 添加根目录选项
    const rootItem = $(`
        <div class="folder-item" data-folder-id="" style="cursor: pointer; padding: 5px; border-radius: 3px;">
            <i class="fas fa-folder text-warning me-2"></i>
            <span>根目录</span>
        </div>
    `);
    container.append(rootItem);
    
    // 递归生成文件夹树
    function addFolderTree(folderList, parentContainer, level = 0) {
        folderList.forEach(function(folder) {
            const hasSubfolders = folder.subfolders && folder.subfolders.length > 0;
            const indent = level * 20;
            
            const folderItem = $(`
                <div class="folder-item" data-folder-id="${folder.id}" style="cursor: pointer; padding: 5px; border-radius: 3px; margin-left: ${indent}px;">
                    ${hasSubfolders ? '<i class="fas fa-chevron-right me-1 folder-toggle" style="font-size: 0.8em;"></i>' : '<span style="width: 12px; display: inline-block;"></span>'}
                    <i class="fas fa-folder text-warning me-2"></i>
                    <span>${folder.name}</span>
                </div>
            `);
            
            parentContainer.append(folderItem);
            
            if (hasSubfolders) {
                const subContainer = $('<div class="subfolder-container" style="display: none;"></div>');
                parentContainer.append(subContainer);
                addFolderTree(folder.subfolders, subContainer, level + 1);
                
                // 添加展开/折叠功能
                folderItem.find('.folder-toggle').on('click', function(e) {
                    e.stopPropagation();
                    const toggle = $(this);
                    const subfolders = folderItem.next('.subfolder-container');
                    
                    if (subfolders.is(':visible')) {
                        subfolders.slideUp(200);
                        toggle.removeClass('fa-chevron-down').addClass('fa-chevron-right');
                    } else {
                        subfolders.slideDown(200);
                        toggle.removeClass('fa-chevron-right').addClass('fa-chevron-down');
                    }
                });
            }
        });
    }
    
    addFolderTree(folders, container);
    
    // 添加文件夹选择功能
    container.on('click', '.folder-item', function(e) {
        if ($(e.target).hasClass('folder-toggle')) return;
        
        // 移除之前的选中状态
        container.find('.folder-item').removeClass('bg-primary text-white').addClass('text-dark');
        
        // 设置当前选中状态
        $(this).addClass('bg-primary text-white').removeClass('text-dark');
        
        // 更新隐藏字段的值
        const folderId = $(this).data('folder-id');
        $('#scriptFolder').val(folderId);
    });
}

function renderFolderTree(folders) {
    const container = $('#scriptsContainer');
    container.empty();
    
    if (folders.length === 0 && currentFolderId === null && (!rootScripts || rootScripts.length === 0)) {
        container.append('<p class="text-muted text-center">暂无文件夹和脚本</p>');
        return;
    }
    
    // 渲染当前文件夹下的内容
    let currentFolder = null;
    if (currentFolderId !== null) {
        currentFolder = findFolderById(folders, currentFolderId);
        if (currentFolder) {
            renderFolderContents(currentFolder);
        }
    } else {
        renderRootContents(folders);
    }
}

function findFolderById(folders, folderId) {
    for (let folder of folders) {
        if (folder.id === folderId) {
            return folder;
        }
        if (folder.subfolders && folder.subfolders.length > 0) {
            const found = findFolderById(folder.subfolders, folderId);
            if (found) return found;
        }
    }
    return null;
}

function renderRootContents(folders) {
    const container = $('#scriptsContainer');
    
    // 渲染文件夹
    folders.forEach(function(folder) {
        container.append(createFolderCard(folder));
    });
    
    // 渲染根目录下的脚本
    if (rootScripts && rootScripts.length > 0) {
        rootScripts.forEach(function(script) {
            container.append(createScriptCard(script));
        });
    }
}

function renderFolderContents(folder) {
    const container = $('#scriptsContainer');
    
    // 返回上级按钮
    if (folder.parent_id !== null) {
        container.append(`
            <div class="card mb-2">
                <div class="card-body d-flex align-items-center">
                    <button class="btn btn-outline-secondary btn-sm" onclick="navigateToParent()">
                        <i class="fas fa-arrow-up me-1"></i>返回上级
                    </button>
                </div>
            </div>
        `);
    }
    
    // 渲染子文件夹
    if (folder.subfolders && folder.subfolders.length > 0) {
        folder.subfolders.forEach(function(subfolder) {
            container.append(createFolderCard(subfolder));
        });
    }
    
    // 渲染脚本
    if (folder.scripts && folder.scripts.length > 0) {
        folder.scripts.forEach(function(script) {
            container.append(createScriptCard(script));
        });
    }
}

// 全局变量用于排序
let currentSortField = 'created_at';
let currentSortOrder = 'asc';
let allItems = []; // 存储所有项目数据

function createFolderRow(folder) {
    const createdAt = new Date(folder.created_at);
    const formattedDate = createdAt.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
    
    return `
        <tr data-item-type="folder" data-item-id="${folder.id}" data-created-at="${folder.created_at}" data-name="${folder.name}" data-type="folder">
            <td>
                <div class="form-check batch-checkbox" style="display: none;">
                    <input class="form-check-input item-checkbox" type="checkbox" data-type="folder" data-id="${folder.id}" onchange="updateBatchSelection()">
                </div>
            </td>
            <td>
                <div class="d-flex align-items-center" style="cursor: pointer;" onclick="navigateToFolder(${folder.id})">
                    <i class="fas fa-folder text-warning me-2"></i>
                    <div class="d-flex align-items-center flex-wrap">
                        <strong class="me-2">${folder.name}</strong>
                        ${folder.description ? '<span class="text-muted small">- ' + folder.description + '</span>' : ''}
                    </div>
                </div>
            </td>
            <td>
                <span class="badge bg-warning item-type-badge">文件夹</span>
            </td>
            <td>
                <span class="created-time">${formattedDate}</span>
            </td>
            <td>
                <div class="script-actions">
                    <button class="action-btn edit-btn" onclick="editFolder(${folder.id}, '${folder.name}', '${folder.description || ''}')" title="编辑文件夹">
                        <i class="fas fa-edit"></i>
                        <span>编辑</span>
                    </button>
                    <button class="action-btn delete-btn" onclick="deleteFolder(${folder.id}, '${folder.name}')" title="删除文件夹">
                        <i class="fas fa-trash"></i>
                        <span>删除</span>
                    </button>
                </div>
            </td>
        </tr>
    `;
}

function createScriptRow(script) {
    const createdAt = new Date(script.created_at);
    const formattedDate = createdAt.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
    
    return `
        <tr data-item-type="script" data-item-id="${script.id}" data-created-at="${script.created_at}" data-name="${script.name}" data-type="script">
            <td>
                <div class="form-check batch-checkbox" style="display: none;">
                    <input class="form-check-input item-checkbox" type="checkbox" data-type="script" data-id="${script.id}" onchange="updateBatchSelection()">
                </div>
            </td>
            <td>
                <div class="d-flex align-items-center" style="cursor: pointer;" onclick="previewScript(${script.id})">
                    <i class="fas fa-file-code text-info me-2"></i>
                    <div class="d-flex align-items-center flex-wrap">
                        <strong class="me-2">${script.name}</strong>
                        ${script.description ? '<span class="text-muted small">- ' + script.description + '</span>' : ''}
                    </div>
                </div>
            </td>
            <td>
                <span class="badge bg-primary item-type-badge">${script.language || 'Python'}</span>
            </td>
            <td>
                <span class="created-time">${formattedDate}</span>
            </td>
            <td>
                <div class="script-actions">
                    <button class="action-btn edit-btn" onclick="editScript(${script.id})" title="编辑脚本">
                        <i class="fas fa-edit"></i>
                        <span>编辑</span>
                    </button>
                    <button class="action-btn download-btn" onclick="downloadScript(${script.id}, '${script.name}')" title="下载脚本">
                        <i class="fas fa-download"></i>
                        <span>下载</span>
                    </button>
                    <button class="action-btn delete-btn" onclick="deleteScript(${script.id}, '${script.name}')" title="删除脚本">
                        <i class="fas fa-trash"></i>
                        <span>删除</span>
                    </button>
                </div>
            </td>
        </tr>
    `;
}

function loadFolderScripts(folderId) {
    const params = folderId !== null ? `?folder_id=${folderId}` : '?folder_id=';
    
    $.get('/api/scripts' + params)
        .done(function(response) {
            if (response.success && response.data.scripts.length > 0) {
                const container = $('#scriptsContainer');
                response.data.scripts.forEach(function(script) {
                    container.append(createScriptCard(script));
                });
            }
        })
        .fail(function() {
            console.error('获取脚本列表失败');
        });
}

function createFolder() {
    $('#folderForm')[0].reset();
    $('#createFolderModal').modal('show');
}

// 脚本上传相关函数已移除

function saveFolder() {
    const name = $('#folderName').val().trim();
    if (!name) {
        showAlert('请输入文件夹名称', 'warning');
        return;
    }
    
    const data = {
        name: name,
        description: $('#folderDescription').val().trim(),
        parent_id: currentFolderId
    };
    
    $.ajax({
        url: '/api/script-folders',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(data),
        dataType: 'json'
    })
        .done(function(response) {
            if (response.success) {
                $('#createFolderModal').modal('hide');
                showAlert('文件夹创建成功', 'success');
                loadScripts();
            } else {
                showAlert('创建失败: ' + response.message, 'danger');
            }
        })
        .fail(function(xhr, status, error) {
            console.log('Error details:', xhr, status, error);
            
            // 尝试解析服务器返回的错误信息
            let errorMessage = '网络错误，请稍后重试';
            if (xhr.responseJSON && xhr.responseJSON.message) {
                errorMessage = xhr.responseJSON.message;
            } else if (xhr.responseText) {
                try {
                    const response = JSON.parse(xhr.responseText);
                    if (response.message) {
                        errorMessage = response.message;
                    }
                } catch (e) {
                    // 解析失败，使用默认错误信息
                }
            }
            
            showAlert(errorMessage, 'danger');
        });
}

function previewScript(scriptId) {
    // 显示加载指示器
    $('#scriptPreview').html(`
        <div class="text-center p-5">
            <div class="spinner-border" role="status"></div>
            <p class="mt-2">加载中...</p>
        </div>
    `);
    
    $.get(`/api/scripts/${scriptId}`)
        .done(function(response) {
            if (response.success) {
                const script = response.data;
                
                // 检查脚本内容是否存在
                let contentDisplay;
                if (!script.content) {
                    contentDisplay = `<div class="alert alert-warning">脚本内容为空或无法读取。请确认脚本文件是否存在。</div>`;
                } else if (script.content.startsWith('# 读取脚本内容失败')) {
                    contentDisplay = `<div class="alert alert-danger">${script.content}</div>`;
                } else {
                    contentDisplay = `<pre style="max-height: 400px; overflow-y: auto; background: #f8f9fa; padding: 10px; border-radius: 5px;"><code>${script.content}</code></pre>`;
                }
                
                $('#scriptPreview').html(`
                    <h6>${script.name}</h6>
                    <p class="text-muted">${script.description || '无描述'}</p>
                    <small class="text-muted">语言: ${script.language}</small>
                    <hr>
                    ${contentDisplay}
                `);
            } else {
                $('#scriptPreview').html(`<div class="alert alert-danger">获取脚本失败: ${response.message}</div>`);
                showAlert('获取脚本失败: ' + response.message, 'danger');
            }
        })
        .fail(function(xhr, status, error) {
            $('#scriptPreview').html(`<div class="alert alert-danger">网络错误: ${status} ${error}</div>`);
            showAlert('网络错误，请稍后重试', 'danger');
            console.error('获取脚本失败:', status, error);
        });
}

function downloadScript(scriptId, scriptName) {
    // 创建一个隐藏的链接来触发下载
    const downloadUrl = `/api/scripts/${scriptId}/download`;
    
    // 创建临时链接元素
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.download = scriptName;
    link.style.display = 'none';
    
    // 添加到页面并触发点击
    document.body.appendChild(link);
    link.click();
    
    // 清理
    document.body.removeChild(link);
    
    // 显示下载提示
    showAlert(`正在下载脚本: ${scriptName}`, 'info');
    
    // 记录下载操作（可选）
    console.log(`下载脚本: ${scriptName} (ID: ${scriptId})`);
}

function deleteScript(scriptId, scriptName) {
    // 创建自定义确认模态框
    const modalHtml = `
        <div class="modal fade" id="deleteScriptModal" tabindex="-1" aria-labelledby="deleteScriptModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header bg-danger text-white">
                        <h5 class="modal-title" id="deleteScriptModalLabel">
                            <i class="fas fa-exclamation-triangle me-2"></i>确认删除脚本
                        </h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <p class="mb-3">您确定要删除脚本 <strong>"${scriptName}"</strong> 吗？</p>
                        <div class="alert alert-warning">
                            <i class="fas fa-info-circle me-2"></i>
                            <strong>注意：</strong>此操作不可撤销！
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-danger" id="confirmDeleteScriptBtn">
                            <i class="fas fa-trash me-2"></i>确认删除
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // 移除已存在的模态框
    $('#deleteScriptModal').remove();
    
    // 添加模态框到页面
    $('body').append(modalHtml);
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('deleteScriptModal'));
    modal.show();
    
    // 绑定确认按钮事件
    $('#confirmDeleteScriptBtn').off('click').on('click', function() {
        modal.hide();
        
        // 执行删除操作
        $.ajax({
            url: `/api/scripts/${scriptId}`,
            method: 'DELETE'
        })
        .done(function(response) {
            if (response.success) {
                showAlert('脚本删除成功', 'success');
                loadScripts();
            } else {
                showAlert('删除失败: ' + response.message, 'danger');
            }
        })
        .fail(function() {
            showAlert('网络错误，请稍后重试', 'danger');
        });
    });
    
    // 模态框关闭时清理
    $('#deleteScriptModal').on('hidden.bs.modal', function() {
        $(this).remove();
    });
}

function navigateToFolder(folderId) {
    currentFolderId = folderId;
    
    // 更新路径
    if (folderId === null) {
        currentPath = [];
    } else {
        // 查找文件夹及其父级路径
        const folderPath = findFolderPath(allFolders, folderId);
        currentPath = folderPath;
    }
    
    // 不再重新加载所有数据，而是直接使用已有的数据重新渲染
    renderFolderTree(allFolders);
    updateBreadcrumb();
}

function findFolderPath(folders, targetId, path = []) {
    for (let folder of folders) {
        const currentPath = [...path, folder];
        if (folder.id === targetId) {
            return currentPath;
        }
        if (folder.subfolders && folder.subfolders.length > 0) {
            const found = findFolderPath(folder.subfolders, targetId, currentPath);
            if (found) return found;
        }
    }
    return null;
}

function updateBreadcrumb() {
    const breadcrumb = $('#breadcrumb');
    breadcrumb.empty();
    
    // 添加根目录
    breadcrumb.append('<li class="breadcrumb-item"><a href="#" onclick="navigateToFolder(null)">根目录</a></li>');
    
    // 添加路径中的每个文件夹
    currentPath.forEach(function(folder, index) {
        const isLast = index === currentPath.length - 1;
        if (isLast) {
            // 最后一个文件夹，显示为当前页面
            breadcrumb.append(`<li class="breadcrumb-item active">${folder.name}</li>`);
        } else {
            // 中间的文件夹，可点击
            breadcrumb.append(`<li class="breadcrumb-item"><a href="#" onclick="navigateToFolder(${folder.id})">${folder.name}</a></li>`);
        }
    });
}

function refreshScripts() {
    // 清除当前状态，重新加载所有数据
    $('#scriptsContainer').html('<div class="text-center p-5"><div class="spinner-border" role="status"></div><p class="mt-2">刷新中...</p></div>');
    loadScripts();
}

function showAlert(message, type) {
    // 使用基础模板中定义的全局showMessage函数（即showToast）
    if (typeof window.showMessage === 'function') {
        // 映射类型到Toast支持的类型
        let toastType = type;
        switch(type) {
            case 'danger':
                toastType = 'error';
                break;
            case 'warning':
                toastType = 'warning';
                break;
            case 'success':
                toastType = 'success';
                break;
            default:
                toastType = 'info';
        }
        showMessage(message, toastType, 3000);
    } else {
        // 如果全局函数不可用，回退到原来的实现
        const alertHtml = `
            <div class="alert alert-${type} alert-dismissible fade show" role="alert">
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;
        
        $('.main-content').prepend(alertHtml);
        
        setTimeout(function() {
            $('.alert').alert('close');
        }, 3000);
    }
}

// 文件夹编辑相关函数
let editingFolderId = null;

function editFolder(folderId, folderName, folderDescription) {
    editingFolderId = folderId;
    $('#editFolderName').val(folderName);
    $('#editFolderDescription').val(folderDescription || '');
    $('#editFolderModal').modal('show');
}

function updateFolder() {
    const name = $('#editFolderName').val().trim();
    if (!name) {
        showAlert('请输入文件夹名称', 'warning');
        return;
    }
    
    const data = {
        name: name,
        description: $('#editFolderDescription').val().trim()
    };
    
    $.ajax({
        url: `/api/script-folders/${editingFolderId}`,
        type: 'PUT',
        contentType: 'application/json',
        data: JSON.stringify(data),
        dataType: 'json'
    })
    .done(function(response) {
        if (response.success) {
            $('#editFolderModal').modal('hide');
            showAlert('文件夹更新成功', 'success');
            loadScripts();
        } else {
            showAlert('更新失败: ' + response.message, 'danger');
        }
    })
    .fail(function(xhr, status, error) {
        console.log('Error details:', xhr, status, error);
        
        // 尝试解析服务器返回的错误信息
        let errorMessage = '网络错误，请稍后重试';
        if (xhr.responseJSON && xhr.responseJSON.message) {
            errorMessage = xhr.responseJSON.message;
        } else if (xhr.responseText) {
            try {
                const response = JSON.parse(xhr.responseText);
                if (response.message) {
                    errorMessage = response.message;
                }
            } catch (e) {
                // 解析失败，使用默认错误信息
            }
        }
        
        showAlert(errorMessage, 'danger');
    });
}

function deleteFolder(folderId, folderName) {
    // 创建自定义确认模态框
    const modalHtml = `
        <div class="modal fade" id="deleteFolderModal" tabindex="-1" aria-labelledby="deleteFolderModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header bg-danger text-white">
                        <h5 class="modal-title" id="deleteFolderModalLabel">
                            <i class="fas fa-exclamation-triangle me-2"></i>确认删除文件夹
                        </h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <p class="mb-3">您确定要删除文件夹 <strong>"${folderName}"</strong> 吗？</p>
                        <div class="alert alert-warning">
                            <i class="fas fa-info-circle me-2"></i>
                            <strong>注意：</strong>普通删除只能删除空文件夹。此操作不可撤销！
                        </div>
                        <div class="form-check mt-3">
                            <input class="form-check-input" type="checkbox" id="forceDeleteCheck">
                            <label class="form-check-label" for="forceDeleteCheck">
                                <i class="fas fa-exclamation-triangle text-warning me-1"></i>
                                <strong>强制删除</strong>（删除文件夹及其所有内容）
                            </label>
                            <div class="form-text text-danger">
                                <small>警告：强制删除将删除文件夹内的所有脚本和子文件夹，无法恢复！</small>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-danger" id="confirmDeleteBtn">
                            <i class="fas fa-trash me-2"></i>确认删除
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // 移除已存在的模态框
    $('#deleteFolderModal').remove();
    
    // 添加模态框到页面
    $('body').append(modalHtml);
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('deleteFolderModal'));
    modal.show();
    
    // 绑定确认按钮事件
    $('#confirmDeleteBtn').off('click').on('click', function() {
        modal.hide();
        
        // 检查是否选择强制删除
        const isForceDelete = $('#forceDeleteCheck').is(':checked');
        
        // 根据选择决定删除方式
        let deleteUrl, deleteMethod;
        if (isForceDelete) {
            // 强制删除
            deleteUrl = `/api/script-folders/${folderId}/force-delete`;
            deleteMethod = 'DELETE';
        } else {
            // 普通删除
            deleteUrl = `/api/script-folders/${folderId}`;
            deleteMethod = 'DELETE';
        }
        
        // 执行删除操作
        $.ajax({
            url: deleteUrl,
            type: deleteMethod
        })
        .done(function(response) {
            if (response.success) {
                const deleteType = isForceDelete ? '强制删除' : '删除';
                showAlert(`文件夹${deleteType}成功`, 'success');
                loadScripts();
            } else {
                showAlert('删除失败: ' + response.message, 'danger');
            }
        })
        .fail(function(xhr, status, error) {
            // 尝试解析服务器返回的错误信息
            let errorMessage = '网络错误，请稍后重试';
            
            if (xhr.responseJSON && xhr.responseJSON.message) {
                errorMessage = xhr.responseJSON.message;
            } else if (xhr.responseText) {
                try {
                    const response = JSON.parse(xhr.responseText);
                    if (response.message) {
                        errorMessage = response.message;
                    }
                } catch (e) {
                    // 如果解析失败，使用默认错误信息
                    console.log('Failed to parse error response:', xhr.responseText);
                }
            }
            
            showAlert(errorMessage, 'danger');
        });
    });
    
    // 模态框关闭时清理
    $('#deleteFolderModal').on('hidden.bs.modal', function() {
        $(this).remove();
    });
}

function navigateToParent() {
    if (currentPath.length > 0) {
        // 如果当前路径不为空，返回上一级文件夹
        const parentFolder = currentPath[currentPath.length - 2];
        currentFolderId = parentFolder ? parentFolder.id : null;
        
        // 更新路径
        if (parentFolder) {
            currentPath = currentPath.slice(0, -1);
        } else {
            currentPath = [];
        }
        
        // 直接使用已有的数据重新渲染，而不是重新加载
        renderFolderTree(allFolders);
        updateBreadcrumb();
    } else {
        // 已经在根目录，不做任何操作
    }
}

function uploadScript() {
    // 更新文件夹选择器
    updateFolderSelect(allFolders);
    
    // 设置当前文件夹为默认选择
    const targetFolderId = currentFolderId || '';
    $('#scriptFolder').val(targetFolderId);
    
    // 高亮显示当前选中的文件夹
    setTimeout(() => {
        const container = $('#folderTreeContainer');
        container.find('.folder-item').removeClass('bg-primary text-white').addClass('text-dark');
        const targetItem = container.find(`[data-folder-id="${targetFolderId}"]`);
        if (targetItem.length > 0) {
            targetItem.addClass('bg-primary text-white').removeClass('text-dark');
        }
    }, 100);
    
    $('#uploadScriptModal').modal('show');
}

function submitUpload() {
    const fileInput = document.getElementById('scriptFile');
    const file = fileInput.files[0];
    
    if (!file) {
        showAlert('请选择要上传的文件', 'danger');
        return;
    }
    
    const formData = new FormData();
    formData.append('file', file);
    formData.append('folder_id', $('#scriptFolder').val() || '');
    formData.append('description', $('#scriptDescription').val());
    
    // 显示上传进度
    const uploadBtn = $('#uploadScriptModal .btn-success');
    const originalText = uploadBtn.text();
    uploadBtn.prop('disabled', true).text('上传中...');
    
    $.ajax({
        url: '/api/scripts/upload',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        xhr: function() {
            const xhr = new window.XMLHttpRequest();
            xhr.upload.addEventListener('progress', function(evt) {
                if (evt.lengthComputable) {
                    const percentComplete = evt.loaded / evt.total * 100;
                    uploadBtn.text(`上传中... ${Math.round(percentComplete)}%`);
                }
            }, false);
            return xhr;
        }
    })
    .done(function(response) {
        if (response.success) {
            $('#uploadScriptModal').modal('hide');
            showAlert('脚本上传成功', 'success');
            loadScripts();
            // 清空表单
            $('#uploadScriptForm')[0].reset();
        } else {
            showAlert('上传失败: ' + response.message, 'danger');
        }
    })
    .fail(function(xhr, status, error) {
        console.log('Upload error:', xhr, status, error);
        showAlert('上传失败，请稍后重试', 'danger');
    })
    .always(function() {
        uploadBtn.prop('disabled', false).text(originalText);
    });
}

// 批量操作相关函数
let batchMode = false;
let selectedItems = {
    scripts: new Set(),
    folders: new Set()
};

// 初始化批量操作模式切换
$(document).ready(function() {
    $('#batchModeToggle').change(function() {
        batchMode = this.checked;
        toggleBatchMode();
    });
});

function toggleBatchMode() {
    const checkboxes = $('.batch-checkbox');
    const toolbar = $('#batchToolbar');
    
    if (batchMode) {
        checkboxes.show();
        toolbar.show();
    } else {
        checkboxes.hide();
        toolbar.hide();
        clearSelection();
    }
}

function updateBatchSelection() {
    selectedItems.scripts.clear();
    selectedItems.folders.clear();
    
    $('.item-checkbox:checked').each(function() {
        const type = $(this).data('type');
        const id = $(this).data('id');
        selectedItems[type + 's'].add(id);
    });
    
    updateBatchToolbar();
}

function updateBatchToolbar() {
    const totalSelected = selectedItems.scripts.size + selectedItems.folders.size;
    $('#selectedCount').text(totalSelected);
    
    // 显示/隐藏相应的批量操作按钮
    $('#batchDeleteScriptsBtn').toggle(selectedItems.scripts.size > 0);
    $('#batchDeleteFoldersBtn').toggle(selectedItems.folders.size > 0);
    $('#batchForceDeleteFoldersBtn').toggle(selectedItems.folders.size > 0);
}

function selectAll() {
    $('.item-checkbox').prop('checked', true);
    updateBatchSelection();
}

function clearSelection() {
    $('.item-checkbox').prop('checked', false);
    updateBatchSelection();
}

function batchDeleteScripts() {
    if (selectedItems.scripts.size === 0) {
        showAlert('请选择要删除的脚本', 'warning');
        return;
    }
    
    const scriptIds = Array.from(selectedItems.scripts);
    const confirmMessage = `确定要删除选中的 ${scriptIds.length} 个脚本吗？此操作不可撤销。`;
    
    if (confirm(confirmMessage)) {
        $.ajax({
            url: '/api/scripts/batch-delete',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ script_ids: scriptIds }),
            success: function(response) {
                if (response.success) {
                    showAlert(`成功删除 ${response.data.deleted_count} 个脚本`, 'success');
                    if (response.data.failed_count > 0) {
                        showAlert(`${response.data.failed_count} 个脚本删除失败`, 'warning');
                    }
                    loadScripts();
                    clearSelection();
                } else {
                    showAlert('批量删除失败: ' + response.message, 'danger');
                }
            },
            error: function() {
                showAlert('批量删除脚本失败，请稍后重试', 'danger');
            }
        });
    }
}

function batchDeleteFolders(forceDelete = false) {
    if (selectedItems.folders.size === 0) {
        showAlert('请选择要删除的文件夹', 'warning');
        return;
    }
    
    const folderIds = Array.from(selectedItems.folders);
    const action = forceDelete ? '强制删除' : '删除';
    const confirmMessage = forceDelete 
        ? `确定要强制删除选中的 ${folderIds.length} 个文件夹吗？这将删除文件夹及其所有内容，此操作不可撤销。`
        : `确定要删除选中的 ${folderIds.length} 个文件夹吗？只有空文件夹才能被删除。`;
    
    if (confirm(confirmMessage)) {
        $.ajax({
            url: '/api/script-folders/batch-delete',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ 
                folder_ids: folderIds,
                force_delete: forceDelete
            }),
            success: function(response) {
                if (response.success) {
                    showAlert(`成功${action} ${response.data.deleted_count} 个文件夹`, 'success');
                    if (response.data.failed_count > 0) {
                        showAlert(`${response.data.failed_count} 个文件夹${action}失败`, 'warning');
                    }
                    loadScripts();
                    clearSelection();
                } else {
                    showAlert(`批量${action}失败: ` + response.message, 'danger');
                }
            },
            error: function() {
                showAlert(`批量${action}文件夹失败，请稍后重试`, 'danger');
            }
        });
    }
}

// 排序功能
function sortBy(field) {
    if (currentSortField === field) {
        // 如果点击的是当前排序字段，切换排序方向
        currentSortOrder = currentSortOrder === 'asc' ? 'desc' : 'asc';
    } else {
        // 如果点击的是新字段，设置为升序
        currentSortField = field;
        currentSortOrder = 'asc';
    }
    
    updateSortIndicators();
    renderSortedItems();
}

function updateSortIndicators() {
    // 清除所有排序指示器
    $('.sort-arrows i').removeClass('active');
    
    // 设置当前排序字段的指示器
    const indicator = currentSortOrder === 'asc' ? 'asc' : 'desc';
    $(`#sort-${currentSortField}-${indicator}`).addClass('active');
}

function renderSortedItems() {
    // 对allItems进行排序
    allItems.sort((a, b) => {
        let aValue, bValue;
        
        switch (currentSortField) {
            case 'name':
                aValue = a.name.toLowerCase();
                bValue = b.name.toLowerCase();
                break;
            case 'type':
                aValue = a.type === 'folder' ? '文件夹' : (a.language || 'Python');
                bValue = b.type === 'folder' ? '文件夹' : (b.language || 'Python');
                break;
            case 'created_at':
                aValue = new Date(a.created_at);
                bValue = new Date(b.created_at);
                break;
            default:
                return 0;
        }
        
        if (aValue < bValue) {
            return currentSortOrder === 'asc' ? -1 : 1;
        }
        if (aValue > bValue) {
            return currentSortOrder === 'asc' ? 1 : -1;
        }
        return 0;
    });
    
    // 重新渲染表格内容
    const container = $('#scriptsContainer');
    container.empty();
    
    // 如果在子文件夹中，添加返回上级按钮
    if (currentFolderId !== null) {
        container.append(`
            <tr>
                <td colspan="5">
                    <button class="btn btn-outline-secondary btn-sm" onclick="navigateToParent()">
                        <i class="fas fa-arrow-up me-1"></i>返回上级
                    </button>
                </td>
            </tr>
        `);
    }
    
    // 渲染排序后的项目
    allItems.forEach(function(item) {
        if (item.type === 'folder') {
            container.append(createFolderRow(item));
        } else {
            container.append(createScriptRow(item));
        }
    });
}

// 修改渲染函数
function renderRootContents(folders) {
    allItems = [];
    
    // 收集所有文件夹数据
    folders.forEach(function(folder) {
        allItems.push({
            ...folder,
            type: 'folder'
        });
    });
    
    // 收集根目录下的脚本数据
    if (rootScripts && rootScripts.length > 0) {
        rootScripts.forEach(function(script) {
            allItems.push({
                ...script,
                type: 'script'
            });
        });
    }
    
    // 应用默认排序并渲染
    renderSortedItems();
}

function renderFolderContents(folder) {
    allItems = [];
    
    // 收集子文件夹数据
    if (folder.subfolders && folder.subfolders.length > 0) {
        folder.subfolders.forEach(function(subfolder) {
            allItems.push({
                ...subfolder,
                type: 'folder'
            });
        });
    }
    
    // 收集脚本数据
    if (folder.scripts && folder.scripts.length > 0) {
        folder.scripts.forEach(function(script) {
            allItems.push({
                ...script,
                type: 'script'
            });
        });
    }
    
    // 应用默认排序并渲染
    renderSortedItems();
}

// 批量操作相关函数
function toggleSelectAll() {
    const selectAllCheckbox = $('#selectAllCheckbox');
    const itemCheckboxes = $('.item-checkbox');
    
    if (selectAllCheckbox.prop('checked')) {
        itemCheckboxes.prop('checked', true);
    } else {
        itemCheckboxes.prop('checked', false);
    }
    
    updateBatchSelection();
}

// 修改批量操作模式切换
$('#batchModeToggle').change(function() {
    const isChecked = $(this).is(':checked');
    
    if (isChecked) {
        $('.batch-checkbox').show();
        $('#selectAllContainer').show();
        $('#batchToolbar').show();
    } else {
        $('.batch-checkbox').hide();
        $('#selectAllContainer').hide();
        $('#batchToolbar').hide();
        clearSelection();
    }
});

// 跳转到脚本编辑页面
function editScript(scriptId) {
    window.location.href = `/dashboard/script-editor/${scriptId}`;
}

// 页面加载完成后设置默认排序
$(document).ready(function() {
    updateSortIndicators();
});


</script>
{% endblock %}